package leetCode;

import java.util.HashMap;
import java.util.Map;

/**
 * @PackageName: leetCode
 * @ClassName: LeetCode560
 * @Author: chen jinxu
 * @Date: 2022/2/15 22:00
 * @Description: //TODO
 *
 * 给你一个整数数组 nums 和一个整数 k ，请你统计并返回该数组中和为 k 的连续子数组的个数。
 * 输入：nums = [1,1,1], k = 2
 * 输出：2
 * 
 * 输入：nums = [1,2,3], k = 3
 * 输出：2
 * 1 <= nums.length <= 2 * 104
 * -1000 <= nums[i] <= 1000
 * -107 <= k <= 107
 */
public class LeetCode560 {
    public static void main(String[] args) {
        int[] nums = {1,1,1};
        int result = subarraySum1(nums, 2);
        int result2 = subarraySum(nums, 2);
        System.out.println(result);
        System.out.println(result2);
    }
    public static int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        // 前缀和
        int pre = 0;
        int count = 0;
        map.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            pre += nums[i];
            if (map.containsKey(pre - k)) {
                count += map.get(pre - k);
            }
            map.put(pre, map.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
    // 枚举法，遍历所有的子数组，并求和， 如果和等于期待值，就 记录
    public static int subarraySum1(int[] nums, int k) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j >= 0; j--) {
                sum += nums[j];
                if (sum == k) {
                    count++;
                }
            }
        }
         return count;
    }
}
